<?php
/*
user_id
user_login
user_password
user_passkey
user_crt_date
user_email
user_recovery_token
user_blocked_date
user_activated_date

*/
class Auth extends CoreModule {
	static protected $ini = null, $mandatory = array(), $auth_form_name = 'login_form_';
	
	
	static function start( array $options=null){
	}
	
	static function init(){
		//global $user_table, $user_data_table;
		
		if(is_null(self::$ini)) {
			self::$ini = array(
				'user_table'=>DB::$tables['user'], 
				'user_data_table'=>DB::$tables['user_data'],
				'cookieTime' => 60*60*24*30*12*5,
			);
			
			self::$mandatory = array(
				'email'=>array('/^\w+([\.\w]+)*\w@\w((\.\w)*\w+)*\.\w{2,3}$/', Lang::get('NO_VALID_EMAIL')),
				'password'=>array('/^[\w\d]{6,30}$/u', Lang::get('PASSWORD_RULES')),
			);
			
		}
	}
	
	/**
	*	Возврат значения одноименного функции массива статического класса
	*
	*	@param string $name ключ массива
	*	@return значение или null
	*/
	static function login_form( $name ){
		$arrName = __FUNCTION__;
		return isset( self::$$arrName[$name] ) ? self::$$arrName[$name] : null ;
	}
	
	static function authentication() {
		self::init();
		/* имя формы, для привязки значений и ошибок полей */
		$form_name = self::$auth_form_name;//'login_form_';
		
		//if( !empty($_SESSION['posttime']) && !empty($_REQUEST['posttime']) && $_SESSION['posttime']==$_REQUEST['posttime'] ){
		   //echo 'form has already been posted! '.$_SESSION['posttime'];
		//}
		//else
		if(!empty($_REQUEST[ 'login_posted' ])){
			if(isset($_REQUEST['posttime']))$_SESSION['posttime']=$_REQUEST['posttime'];
		
			$_REQUEST['remember'] = isset( $_REQUEST['remember'] ) ? 1 : 0;
			
			$errs = Form::checkFields( self::$mandatory ); 
			//Form::error( $form_name, 'fields', $errs );/* запись ошибок заполнения полей по имени формы */
			if(count( $errs )<1){
			
				$userData = exec_sql2fields("SELECT * FROM `".self::$ini['user_table']."` AS user ".
					"JOIN `".self::$ini['user_data_table']."` AS data ON data.ud_user_id=user.user_id ".
					"WHERE ".
					"user.user_email='".db_escape( $_REQUEST['email'] )."' AND ".
					"user.user_password='".md5( md5( $_REQUEST['password'] ) )."' AND ".
					"ISNULL(`user_blocked_date`) AND NOT ISNULL(`user_activated_date`);");

				if ( count( $userData ) > 0 ) {

					if ( $_REQUEST['remember'] == 1 ) {
						SetCookie("ruirm",
							md5( 
								$userData['user_passkey'].
								md5( $userData['user_id'] ).
								md5( $_REQUEST['email'] ).
								md5( md5( md5( $_REQUEST['password'] ) ) ) 
							),
							time() + self::$ini['cookieTime'], "/"//, ".".$GLOBALS['settings']['base_domain']
						);
					}

					$_SESSION['user'] = $userData;
					$_SESSION['user']['sign'] = true;
					
					if(!empty($_SESSION['redirect'])){
						$_SESSION['redirect'] = str_replace( 'logout=', 'login=', $_SESSION['redirect'] );
						redirect( $_SESSION['redirect'] );
						unset( $_SESSION['redirect'] );
						exit;
					}
					//foreach( $_REQUEST as $name=>$value ) Form::value( $form_name.$name, '');
				} else {
					Form::error( $form_name, 'email', Lang::get('NO_VALID_LOGIN_OR_PASS') );
					foreach( $_REQUEST as $name=>$value ) Form::value( $form_name, $name, $value);
				}	
				
			} else {
				foreach( $_REQUEST as $name=>$value ) {
					Form::value( $form_name, $name, $value);
					if(!empty( $errs[ $name ])) Form::error( $form_name, $name, $errs[$name] );
				} 
			}
			
		}
	}
	
	static function logout(){
		self::init();
		
		if (isset($_SESSION['user'])) {
				SetCookie("ruirm", '', time() + self::$ini['cookieTime'], "/"//, ".".$GLOBALS['settings']['base_domain']
			);//
			
			if(isset($_SESSION['user']['user_id']) )
				exec_sql( "UPDATE `".self::$ini['user_table']."` SET `user_passkey`='".time()."' WHERE `user_id`='".$_SESSION['user']['user_id']."';");
			unset($_SESSION['user']);
			
			//$parse_url = _parse_url( $_SERVER['REQUEST_URI'] );
			//redirect( $parse_url['path'] );
		}
	}
	
	/**
	*  Проверяем данные пользователя, куки, сессию и т.д.
	*/
	static function checkUser() {
		self::init(); 
		
		if ( !isset( $_SESSION['user'] ) ) { 
			$_SESSION['user'] = array(
				'sign' => false,
				'access' => array(),
			);
		}

		if ( isset( $_COOKIE['ruirm'] ) ) {
		
			$sql = "SELECT * FROM `".self::$ini['user_table']."` AS user ".
				"JOIN `".self::$ini['user_data_table']."` AS data ON data.ud_user_id=user.user_id ".
				"WHERE md5(CONCAT(`user_passkey`, md5(`user_id`), md5(`user_email`), md5(`user_password`)))='".db_escape( $_COOKIE['ruirm'] )."' ".
					"AND ISNULL(`user_blocked_date`) ".
					"AND NOT ISNULL(`user_activated_date`);";
			
			$userData = exec_sql2fields( $sql );

			if ( count( $userData ) > 0 ) {

				$_SESSION['user'] = $userData;
				$_SESSION['user']['sign'] = true;

				SetCookie( "ruirm", $_COOKIE['ruirm'], time() + self::$ini['cookieTime'], "/");//, ".".$GLOBALS['settings']['base_domain'] 

			} else {

				SetCookie( "PHPSESSID", '', time() + self::$ini['cookieTime'], "/"//, ".".$GLOBALS['settings']['base_domain'] 
				);
				SetCookie( "ruirm", '', time() + self::$ini['cookieTime'], "/"//, ".".$GLOBALS['settings']['base_domain'] 
				);
				$_SESSION['user']['sign'] = false;
				$_SESSION['user']['access'] = array();
				$_SESSION['user']['info'] = 'isset( $_COOKIE[ruirm] )'.$sql;
			}
		} else if ( $_SESSION['user']['sign'] ) { 

			$userData = exec_sql2fields(
				"SELECT * FROM `".self::$ini['user_table']."` AS user ".
				"JOIN `".self::$ini['user_data_table']."` AS data ON data.ud_user_id=user.user_id ".
					"WHERE user.user_id='".$_SESSION['user']['user_id']."' ".
					"AND ISNULL(`user_blocked_date`) ".
					"AND NOT ISNULL(`user_activated_date`);"
			);

			if ( ( count( $userData ) > 0 ) && ( $userData['user_passkey'] == $_SESSION['user']['user_passkey'] ) ) {

				$_SESSION['user'] = $userData;
				$_SESSION['user']['sign'] = true;

			} else {
				$_SESSION['user']['sign'] = false;
				$_SESSION['user']['access'] = array();
				$_SESSION['user']['info'] = '$_SESSION[user][sign]';
			}
		}
		
		if($_SESSION['user']['sign']){
			define( "IS_AUTH", true );
			$_SESSION['user']['access'] = exec_sql2list('SELECT `ua_type_id` FROM `'.DB::$tables['user_access'].'` WHERE `ua_user_id`="'.$_SESSION['user']['user_id'].'";');
			if( in_array( 1, $_SESSION['user']['access'] ) ) { define( "IS_ADMIN", true ); };
		} else {
			define( "IS_AUTH", false ); define( "IS_ADMIN", false );
		}
		
	}
	
	
	/**
	*	Вывод шаблона c результатами работы модуля
	*	
	*	@param $options - массив опций
	*	@return string 
	*/
	static function Out( array $options=null ) {
		if(is_array($options)) self::$ini = $options+self::$ini;
		self::$ini['__CLASS__'] = __CLASS__;
		
		self::start();
		ob_start();
			self::includeTemplate( self::$ini );
		$out = ob_get_clean();
		return $out;
	}
	
}
?>